package org.egedede.osgi.guishell.model.commands;

import java.io.PrintStream;
import java.util.Date;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Properties;

import org.egedede.osgi.guishell.model.AbstractCommand;
import org.egedede.osgi.guishell.model.CommandType;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;

public class BundleInfoCommand extends AbstractCommand {

	public BundleInfoCommand(){
		super("Info", "Get some information from bundle",CommandType.BUNDLE);
	}
	public Object execute(Properties properties, PrintStream out, PrintStream error) {
		try{
		Object property = properties.get("bundle.id");
		long parseInt = (Long)property;
		Bundle bundle = getContext().getBundle(parseInt);
		StringBuffer result = new StringBuffer("");
		result.append("Id : ");
		result.append(bundle.getBundleId());
		result.append("\n");
		result.append("Symbolic name : ");
		result.append(bundle.getSymbolicName());
		result.append("\n");
		result.append("Last modified : ");
		result.append(new Date(bundle.getLastModified()));
		result.append("\n");
		result.append("Location : ");
		result.append(bundle.getLocation());
		result.append("\n");
		result.append("State : ");
		result.append(bundle.getState());
		result.append("\n");
		result.append("Headers : ");
		result.append("\n");
		Dictionary headers = bundle.getHeaders();
		Enumeration keys = headers.keys();
		while(keys.hasMoreElements()){
			Object key = keys.nextElement();
			result.append("\tkey :");
			result.append(key);
			result.append(" => value :");
			result.append(headers.get(key));
			result.append("\n");
		}
		result.append("Services : ");
		ServiceReference[] services = bundle.getRegisteredServices();
		if(services ==null){
			result.append("none\n");
		}else{
			for(int i=0;i<services.length; i++){
				ServiceReference reference = services[i];
				result.append("\tService :");
				result.append(reference);
				result.append("\n");
			}
		}
		return result.toString();
		}catch(Exception e){
			e.printStackTrace(error);
			return e.getStackTrace().toString();
		}
	}

}
